package com.example.uupaymuch.controller.telegram;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageReplyMarkup;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootApplication
public class TelegramBotDemo extends TelegramLongPollingBot {


    public TelegramBotDemo() {
        this(new DefaultBotOptions());
    }

    public TelegramBotDemo(DefaultBotOptions options) {
        super(options);
    }

    @Override
    public String getBotUsername() {
        return "nier73_bot"; // 替换为您的Bot用户名
    }

    @Override
    public String getBotToken() {
        return "6508859688:AAGpNHL9VABxDxcCQT-033aR-BtyqDLs8EI"; // 替换为您的Bot令牌
    }

    @Override
    public void onUpdateReceived(Update update) {
        if (update.hasMessage()) {
//            Map<String, String> resultMap = JSON.parseObject(update.getCallbackQuery().getData(), Map.class);
//            String firstName = update.getCallbackQuery().getFrom().getFirstName();
            // 处理消息
            handleIncomingMessage(update);
        } else if (update.hasCallbackQuery()) {
            // 处理回调查询
            if (true) {
                answerCallbackQuery(update.getCallbackQuery().getId(), true);
            }
            Boolean isAdmin = handleReply(update); // 是否是管理员
            editMessage(update.getCallbackQuery().getMessage().getMessageId(), "审批通过: 订单好TX123", update.getCallbackQuery().getMessage().getChatId());
        }
    }

    private void handleIncomingMessage(Update update) {
        Message message = update.getMessage();
        String chatId = String.valueOf(message.getChatId());
        // 创建内联键盘
        InlineKeyboardMarkup markup = new InlineKeyboardMarkup();

        // 创建第一个按钮
        Map<String, String> param1 = new HashMap<>();
        param1.put("state", "1");
        param1.put("myData", "123测试");
        InlineKeyboardButton btn1 = new InlineKeyboardButton();
        btn1.setText("✅通过");
        btn1.setCallbackData(JSON.toJSONString(param1)); // 使用 JSON 作为回调数据

        // 创建第二个按钮
        Map<String, String> param2 = new HashMap<>();
        param2.put("state", "2");
        param2.put("myData", "随便填写你的参数，后面触发按钮时会将你的参数完整的返回给你");
        InlineKeyboardButton btn2 = new InlineKeyboardButton();
        btn2.setText("❌驳回");
        btn2.setCallbackData(JSON.toJSONString(param2)); // 使用 JSON 作为回调数据

        // 将按钮添加到同一行
        List<InlineKeyboardButton> row = new ArrayList<>();
        row.add(btn1);
        row.add(btn2);

        // 创建一个列表并添加行
        List<List<InlineKeyboardButton>> buttons = new ArrayList<>();
        buttons.add(row);

        // 设置键盘
        markup.setKeyboard(buttons);

        // 发送消息
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        sendMessage.setText("测试审核");
        sendMessage.setReplyMarkup(markup);
        try {
            execute(sendMessage);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    public Boolean handleReply(Update update) {
        // 检查更新是否包含回复消息
        if (update.getCallbackQuery() != null) {
            CallbackQuery callbackQuery = update.getCallbackQuery();
            Long userId = callbackQuery.getFrom().getId(); // 获取回复者的用户 ID
            Long chatId = callbackQuery.getMessage().getChatId(); // 获取群聊 ID

            // 创建 GetChatMember 请求
            GetChatMember getChatMember = new GetChatMember();
            getChatMember.setChatId(String.valueOf(chatId));
            getChatMember.setUserId(userId);

            try {
                // 执行请求并获取 ChatMember 信息
                ChatMember chatMember = execute(getChatMember);

                // 检查用户角色
                if ("administrator".equals(chatMember.getStatus()) || "creator".equals(chatMember.getStatus())) {
                    // 用户是超级管理员或群主
                    System.out.println("用户是超级管理员或群主。");
                    return true;
                } else {
                    // 用户不是超级管理员
                    System.out.println("用户不是超级管理员。");
                    return false;
                }
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public void answerCallbackQuery(String messageId, Boolean showAlert) {

        // 创建 GetChatMember 请求
        AnswerCallbackQuery answerCallbackQuery = new AnswerCallbackQuery();
        answerCallbackQuery.setCallbackQueryId(messageId);
        answerCallbackQuery.setText("你不是管理员");
        answerCallbackQuery.setShowAlert(showAlert);

        try {
            // 执行请求并获取 ChatMember 信息
            Boolean execute = execute(answerCallbackQuery);

        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    private void editMessage(Integer messageId, String text, Long chatId) {

        EditMessageText editMessage = new EditMessageText();
        editMessage.setMessageId(messageId);
        editMessage.setChatId(String.valueOf(chatId));
        editMessage.setText(text);
        try {
            execute(editMessage); // 发送编辑消息请求
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}